/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojo.Address;
import pojo.Orderdetail;
import java.util.ArrayList;
import java.util.Collection;
import pojo.Userorder;

/**
 *
 * @author A7med Kotb
 */
public class UserorderJpaController implements Serializable {

    public UserorderJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Userorder userorder) throws RollbackFailureException, Exception {
        if (userorder.getOrderdetailCollection() == null) {
            userorder.setOrderdetailCollection(new ArrayList<Orderdetail>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Address addressId = userorder.getAddressId();
            if (addressId != null) {
                addressId = em.getReference(addressId.getClass(), addressId.getId());
                userorder.setAddressId(addressId);
            }
            Collection<Orderdetail> attachedOrderdetailCollection = new ArrayList<Orderdetail>();
            for (Orderdetail orderdetailCollectionOrderdetailToAttach : userorder.getOrderdetailCollection()) {
                orderdetailCollectionOrderdetailToAttach = em.getReference(orderdetailCollectionOrderdetailToAttach.getClass(), orderdetailCollectionOrderdetailToAttach.getId());
                attachedOrderdetailCollection.add(orderdetailCollectionOrderdetailToAttach);
            }
            userorder.setOrderdetailCollection(attachedOrderdetailCollection);
            em.persist(userorder);
            if (addressId != null) {
                addressId.getUserorderCollection().add(userorder);
                addressId = em.merge(addressId);
            }
            for (Orderdetail orderdetailCollectionOrderdetail : userorder.getOrderdetailCollection()) {
                Userorder oldUserOrderIdOfOrderdetailCollectionOrderdetail = orderdetailCollectionOrderdetail.getUserOrderId();
                orderdetailCollectionOrderdetail.setUserOrderId(userorder);
                orderdetailCollectionOrderdetail = em.merge(orderdetailCollectionOrderdetail);
                if (oldUserOrderIdOfOrderdetailCollectionOrderdetail != null) {
                    oldUserOrderIdOfOrderdetailCollectionOrderdetail.getOrderdetailCollection().remove(orderdetailCollectionOrderdetail);
                    oldUserOrderIdOfOrderdetailCollectionOrderdetail = em.merge(oldUserOrderIdOfOrderdetailCollectionOrderdetail);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Userorder userorder) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Userorder persistentUserorder = em.find(Userorder.class, userorder.getId());
            Address addressIdOld = persistentUserorder.getAddressId();
            Address addressIdNew = userorder.getAddressId();
            Collection<Orderdetail> orderdetailCollectionOld = persistentUserorder.getOrderdetailCollection();
            Collection<Orderdetail> orderdetailCollectionNew = userorder.getOrderdetailCollection();
            List<String> illegalOrphanMessages = null;
            for (Orderdetail orderdetailCollectionOldOrderdetail : orderdetailCollectionOld) {
                if (!orderdetailCollectionNew.contains(orderdetailCollectionOldOrderdetail)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Orderdetail " + orderdetailCollectionOldOrderdetail + " since its userOrderId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (addressIdNew != null) {
                addressIdNew = em.getReference(addressIdNew.getClass(), addressIdNew.getId());
                userorder.setAddressId(addressIdNew);
            }
            Collection<Orderdetail> attachedOrderdetailCollectionNew = new ArrayList<Orderdetail>();
            for (Orderdetail orderdetailCollectionNewOrderdetailToAttach : orderdetailCollectionNew) {
                orderdetailCollectionNewOrderdetailToAttach = em.getReference(orderdetailCollectionNewOrderdetailToAttach.getClass(), orderdetailCollectionNewOrderdetailToAttach.getId());
                attachedOrderdetailCollectionNew.add(orderdetailCollectionNewOrderdetailToAttach);
            }
            orderdetailCollectionNew = attachedOrderdetailCollectionNew;
            userorder.setOrderdetailCollection(orderdetailCollectionNew);
            userorder = em.merge(userorder);
            if (addressIdOld != null && !addressIdOld.equals(addressIdNew)) {
                addressIdOld.getUserorderCollection().remove(userorder);
                addressIdOld = em.merge(addressIdOld);
            }
            if (addressIdNew != null && !addressIdNew.equals(addressIdOld)) {
                addressIdNew.getUserorderCollection().add(userorder);
                addressIdNew = em.merge(addressIdNew);
            }
            for (Orderdetail orderdetailCollectionNewOrderdetail : orderdetailCollectionNew) {
                if (!orderdetailCollectionOld.contains(orderdetailCollectionNewOrderdetail)) {
                    Userorder oldUserOrderIdOfOrderdetailCollectionNewOrderdetail = orderdetailCollectionNewOrderdetail.getUserOrderId();
                    orderdetailCollectionNewOrderdetail.setUserOrderId(userorder);
                    orderdetailCollectionNewOrderdetail = em.merge(orderdetailCollectionNewOrderdetail);
                    if (oldUserOrderIdOfOrderdetailCollectionNewOrderdetail != null && !oldUserOrderIdOfOrderdetailCollectionNewOrderdetail.equals(userorder)) {
                        oldUserOrderIdOfOrderdetailCollectionNewOrderdetail.getOrderdetailCollection().remove(orderdetailCollectionNewOrderdetail);
                        oldUserOrderIdOfOrderdetailCollectionNewOrderdetail = em.merge(oldUserOrderIdOfOrderdetailCollectionNewOrderdetail);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = userorder.getId();
                if (findUserorder(id) == null) {
                    throw new NonexistentEntityException("The userorder with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Userorder userorder;
            try {
                userorder = em.getReference(Userorder.class, id);
                userorder.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The userorder with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Orderdetail> orderdetailCollectionOrphanCheck = userorder.getOrderdetailCollection();
            for (Orderdetail orderdetailCollectionOrphanCheckOrderdetail : orderdetailCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Userorder (" + userorder + ") cannot be destroyed since the Orderdetail " + orderdetailCollectionOrphanCheckOrderdetail + " in its orderdetailCollection field has a non-nullable userOrderId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Address addressId = userorder.getAddressId();
            if (addressId != null) {
                addressId.getUserorderCollection().remove(userorder);
                addressId = em.merge(addressId);
            }
            em.remove(userorder);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Userorder> findUserorderEntities() {
        return findUserorderEntities(true, -1, -1);
    }

    public List<Userorder> findUserorderEntities(int maxResults, int firstResult) {
        return findUserorderEntities(false, maxResults, firstResult);
    }

    private List<Userorder> findUserorderEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Userorder.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Userorder findUserorder(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Userorder.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserorderCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Userorder> rt = cq.from(Userorder.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
